package com.friend.chat.media.audio

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.friend.chat.R
import com.friend.chat.chat.CHAT_SYSTEM
import com.friend.chat.chat.CHAT_TEXT
import com.friend.chat.page.bean.UserBean
import com.friend.chat.utils.BurredUtil
import com.friend.chat.utils.SPUtils
import com.friend.chat.utils.Speex
import com.friend.chat.websocket.ChatMessageBean
import com.friend.chat.websocket.WebSocketManager
import com.google.gson.Gson
import com.permissionx.guolindev.PermissionX
import com.zackratos.ultimatebarx.ultimatebarx.navigationBar
import com.zackratos.ultimatebarx.ultimatebarx.statusBar
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.toast
import java.util.*
import kotlin.concurrent.schedule

class AudioActivity : AppCompatActivity() {

    private var isCall: Boolean = true
    private var mToUid: String = ""
    private lateinit var userBean: UserBean
    private lateinit var pickupView: ImageView
    private lateinit var hangupView: ImageView
    private lateinit var backgroundView:ImageView
    private var mMediaPlayerHangup: MediaPlayer? = null
    //接听的时候响铃
    private var mMediaPlayerRingPickup: MediaPlayer? = null
    //拨打的时候响铃
    private var mMediaPlayerRingCall: MediaPlayer? = null
    companion object {
        fun open(activity: Activity, toUid: String, isCall: Boolean) {
            val intent = Intent(activity, AudioActivity::class.java)
            intent.putExtra("toUid", toUid)
            //接电话或者是打电话
            intent.putExtra("isCall", isCall)
            activity.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_audio)
        statusBar { transparent() }
        navigationBar { transparent() }
        mMediaPlayerHangup = MediaPlayer.create(this, R.raw.hangup)
        mMediaPlayerRingPickup = MediaPlayer.create(this,R.raw.phone_ring_pickup)
        mMediaPlayerRingPickup?.isLooping = true
        mMediaPlayerRingCall  = MediaPlayer.create(this,R.raw.phone_ring_call)
        mMediaPlayerRingCall?.setOnCompletionListener {
            Timer().schedule(800){
                mMediaPlayerRingCall?.start()
            }
        }
        mMediaPlayerRingCall?.isLooping = false


        pickupView = findViewById(R.id.calling_pickup)
        hangupView = findViewById(R.id.calling_hangup)
        backgroundView = findViewById(R.id.iv_back)

        val bitmap = BitmapFactory.decodeResource(resources, R.drawable.background_4)
        val a  = BurredUtil.createBlurredImageFromBitmap(bitmap,this,60)
        backgroundView.setImageDrawable(a)
       /* val bitmap1 = Mohu.rsBlur(this, bitmap, 10);//10:模糊半径，范围1-25，越大图片越模糊
        backgroundView.setImageBitmap(bitmap1);*/


        userBean = SPUtils.getInstance().getObject("user") as UserBean
        isCall = intent.getBooleanExtra("isCall", true)
        mToUid = intent.getStringExtra("toUid") ?: ""
        Log.e("---->toUid", mToUid)
        initView()
        initClick()
    }

    private fun initClick() {
        //接听
        pickupView.setOnClickListener {
            WebSocketManager.instance.sendMessage(
                Gson().toJson(
                    ChatMessageBean(
                        userBean.uid,
                        toUid = mToUid,
                        type = CHAT_SYSTEM,
                        roomType = -1,
                        PICKUP_AUDIO_ACK
                    )
                )
            )
            pickupView.visibility = View.GONE
            hangupView.visibility = View.VISIBLE
            mMediaPlayerRingPickup?.stop()
            AudioRecorder.getInstance()?.startRecord(
                this@AudioActivity,
                uid = userBean.uid,
                toUid = mToUid
            )
        }

        //挂断
        hangupView.setOnClickListener {
            AudioRecorder.getInstance()?.stopRecording()
            AudioDecoder.getInstance().stopDecoding()
            WebSocketManager.instance.sendMessage(
                Gson().toJson(
                    ChatMessageBean(
                        userBean.uid,
                        mToUid, type = CHAT_SYSTEM,
                        roomType = -1,
                        HANGUP_AUDIO_ACK
                    )
                )
            )
            mMediaPlayerRingCall?.stop()
            mMediaPlayerHangup?.start()
            mMediaPlayerHangup?.setOnCompletionListener {
                finish()
            }
        }

    }

    private fun initView() {

        if (isCall) {
            pickupView.visibility = View.GONE
            hangupView.visibility = View.VISIBLE
        } else {
            pickupView.visibility = View.VISIBLE
            hangupView.visibility = View.GONE
        }
        PermissionX.init(this).permissions(Manifest.permission.RECORD_AUDIO)
            .request { allGranted, _, _ ->
                if (allGranted) {
                    try {
                        Speex.getInstance().init()
                    } catch (e: Exception) {

                    }
                    if (isCall) {
                        WebSocketManager.instance.sendMessage(
                            Gson().toJson(
                                ChatMessageBean(
                                    userBean.uid,
                                    mToUid,
                                    type = CHAT_SYSTEM,
                                    roomType = -1,
                                    CALL_AUDIO_ACK
                                )
                            )
                        )
                        mMediaPlayerRingCall?.start()

                    }else{
                        //有电话进来
                        mMediaPlayerRingPickup?.start()
                    }
                }
            }

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: ChatMessageBean?) {
        event?.apply {
            if (event.type == CHAT_SYSTEM && PICKUP_AUDIO_ACK == event.message) {
                //对方已接听，开始录制
                mMediaPlayerRingCall?.stop()
                mMediaPlayerRingCall = null
                Log.e("--->", "对方已接听，开始录制")
                AudioRecorder.getInstance()?.startRecord(
                    this@AudioActivity, uid = userBean.uid, toUid = mToUid
                )

            } else if (event.type == CHAT_SYSTEM && HANGUP_AUDIO_ACK == event.message) {
                toast("对方已挂断电话")
                mMediaPlayerHangup?.start()
                AudioRecorder.getInstance()?.stopRecording()
                AudioDecoder.getInstance().stopDecoding()
                Timer().schedule(1000) {
                    finish()
                }
            } else if (event.type == 5) {
                Log.e("--->", "对方已接听，开始播放")
                var data: ArrayList<Byte> = event.message as ArrayList<Byte>
                AudioDecoder.getInstance().addData(data.toByteArray(), data.size)
            }
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this)
        }
        mMediaPlayerRingCall?.stop()
        mMediaPlayerRingCall = null
        mMediaPlayerRingPickup?.stop()
        mMediaPlayerRingPickup = null
        mMediaPlayerHangup?.stop()
        mMediaPlayerHangup = null
        super.onDestroy()

    }
}